<template>
  <div class="login-container">
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        autocomplete
        :rules="[{ required: true, message: '请填写用户名' }]"
      />

      <van-field
        v-model="form.password"
        type="password"
        name="密码"
        autocomplete
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />

      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>

    <div class="text">
      <router-link to="/register">没有账号？立即注册</router-link>
    </div>
  </div>
</template>

<script>
// let obj = {} // 原始plain object
import { reqLogin } from '@/api/user'
export default {
  data() {
    return {
      form: {
        username: '',
        password: '',
      },
    }
  },
  methods: {
    async onSubmit() {
      let { status, message, token, refreshToken, userInfo } = await reqLogin(this.form)
      if (status === 0) {
        // 1. 将token和userinfo存入到vuex
        this.$store.commit('setToken', { token, refreshToken })
        this.$store.commit('setUserInfo', userInfo)

        // 2. 跳到首页
        let redirect = this.$route.query.redirect
        this.$router.push(redirect || '/home')
      } else {
        this.$toast(message)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.login-container {
  padding-top: 20px;

  .text {
    text-align: center;

    a {
      color: rgb(185 181 181);
    }
  }
}
</style>
